package vip.sone.util;

import com.alibaba.druid.pool.DruidDataSource;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;

import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

//@PropertySource(value = "classpath:jdbc.properties")
public class JdbcTemplateUtil {
    private static final Logger log = LoggerFactory.getLogger(JdbcTemplateUtil.class);

//    @Value("#{jdbc.driver}")
    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    @Test
    public void test() {
        JdbcTemplate jdbcTemplate = JdbcTemplateUtil.jdbcTemplate();
    }

    private static Properties properties;
    static {
        properties = new Properties();
        try {
//        System.out.println(JdbcTemplateUtil.class.getClassLoader().getResource("/").getPath());
//        System.out.println(JdbcTemplateUtil.class.getClassLoader().getResource("/jdbc.properties").getPath());
            //properties.load(String.class.getResourceAsStream("/jdbc.properties"));
            properties.load(new FileReader(JdbcTemplateUtil.class.getClassLoader().getResource("jdbc.properties").getPath()));
            url = properties.getProperty("jdbc.url");
            driver = properties.getProperty("jdbc.driver");
            username = properties.getProperty("jdbc.username");
            password = properties.getProperty("jdbc.password");
        } catch (IOException e) {
             e.printStackTrace();
        }
    }

    private static JdbcTemplate jdbcTemplate;
    public static JdbcTemplate jdbcTemplate() {
        if (null == jdbcTemplate) {
            jdbcTemplate = createJdbcTemplate();
        }
        return jdbcTemplate;
    }

    private static JdbcTemplate createJdbcTemplate() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        return new JdbcTemplate(dataSource);
    }
}
